//
//  RLSelectDateView.m
//  SafePeriod
//
//  Created by SL on 14-1-6.
//  Copyright (c) 2014年 cdeledu. All rights reserved.
//

#import "SelectPickerView.h"
#import "NationClass.h"

//身高
#define SG_MAX      200.0
#define SG_MIN      120.0

//婴儿身高
#define YE_SG_MAX   90.0
#define YE_SG_MIN   30.0

//体重
#define TZ_MAX      100
#define TZ_MIN      40

//婴儿体重
#define YE_TZ_MAX      15.0
#define YE_TZ_MIN      0.0

//宫高
#define GG_MAX   40.0
#define GG_MIN   12.0

//腹围
#define FW_MAX   120
#define FW_MIN   60

//背景view tag
#define BgViewTag           5437
#define UIDatePickerTag     5764

@interface SelectPickerView()<UIPickerViewDataSource,UIPickerViewDelegate,ASIHTTPRequestDelegate>
{
    NSArray *oneArray;
    NSArray *twoArray;

    NSInteger currentType;
}
@end

@implementation SelectPickerView

@synthesize delegate;

//
-(void)setShowView:(int)type text:(NSString*)oldText
{
    currentType = type;
    
    //是否使用UIDatePicker
    BOOL datePick = NO;
    
    switch (type) {
        case CSRQ_TYPE:
        case YE_CSRQ_TYPE:
        case MCYJ_TYPE:
        case SZ_CZTX_TZ:
        {
            datePick = YES;
        }
            break;
        case SG_YF_TYPE:
        case FW_TYPE:
        {
            NSInteger min,max;
            if (type == SG_YF_TYPE) {
                min = SG_MIN;
                max = SG_MAX;
            }else{
                min = FW_MIN;
                max = FW_MAX;
            }
            
            NSMutableArray *array = [NSMutableArray arrayWithCapacity:1];
            NSInteger m = min;
            for (int i = 0 ; i <= max-min; i++) {
                [array addObject:[NSString stringWithFormat:@"%d%@",m,APP_LENGTH_UNIT]];
                m++;
            }
            oneArray = [[NSArray alloc] initWithArray:array];
        }
            break;
        case SG_YE_TYPE:
        case GG_TYPE:
        {
            NSInteger min,max;
            if (type == SG_YE_TYPE) {
                min = YE_SG_MIN;
                max = YE_SG_MAX;
            }else{
                min = GG_MIN;
                max = GG_MAX;
            }
            
            NSMutableArray *array = [NSMutableArray arrayWithCapacity:1];
            NSInteger m = min;
            for (int i = 0 ; i < max-min; i++) {
                
                [array addObject:[NSString stringWithFormat:@"%.1d",m]];
                m++;
            }
            oneArray = [[NSArray alloc] initWithArray:array];
            
            NSMutableArray *array1 = [NSMutableArray arrayWithCapacity:1];
            CGFloat c = 0.0;
            for (int i = 0 ; i < 10; i++) {
                NSString *text = [NSString stringWithFormat:@"%.1f%@",c,APP_LENGTH_UNIT];
                [array1 addObject:[text substringFromIndex:1]];
                c+=0.1;
            }
            twoArray = [[NSArray alloc] initWithArray:array1];
        }
            break;
        case XZMZ_TYPE:
        {
            NSArray *array = [NationClass getNationData];
//            if (!array) {
//                return;
//            }
//            for (NSDictionary *dic in array) {
//                if ([oldText isEqualToString:[dic valueForKeyPath:@"id"]]) {
//                    oldText = [dic valueForKeyPath:@"nation"];
//                    break;
//                }
//            }
//            NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"nation" ofType:@"plist"]];
            oneArray = array;
        }
            break;
        case SEX_TYPE:
        {
            oneArray = @[@"男",@"女"];
        }
            break;
        case YQTZ_TYPE:
        {
            NSMutableArray *array = [NSMutableArray arrayWithCapacity:1];
            NSInteger m = TZ_MIN;
            for (int i = 0 ; i < TZ_MAX-TZ_MIN; i++) {
                [array addObject:[NSString stringWithFormat:@"%d",m]];
                m++;
            }
            oneArray = [[NSArray alloc] initWithArray:array];
            
            NSMutableArray *array1 = [NSMutableArray arrayWithCapacity:1];
            CGFloat c = 0.0;
            for (int i = 0 ; i < 10; i++) {
                NSString *text = [NSString stringWithFormat:@"%.1f%@",c,APP_WEIGHT_UNIT];
                [array1 addObject:[text substringFromIndex:1]];
                c+=0.1;
            }
            twoArray = [[NSArray alloc] initWithArray:array1];
        }
            break;
        case YETZ_TYPE:
        {
            NSMutableArray *array = [NSMutableArray arrayWithCapacity:1];
            NSInteger m = YE_TZ_MIN;
            for (int i = 0 ; i < YE_TZ_MAX-YE_TZ_MIN; i++) {
                [array addObject:[NSString stringWithFormat:@"%d",m]];
                m++;
            }
            oneArray = [[NSArray alloc] initWithArray:array];
            
            NSMutableArray *array1 = [NSMutableArray arrayWithCapacity:1];
            CGFloat c = 0.0;
            for (int i = 0 ; i < 100; i++) {
                NSString *text = [NSString stringWithFormat:@"%.2f%@",c,APP_WEIGHT_UNIT];
                [array1 addObject:[text substringFromIndex:1]];
                c+=0.01;
            }
            twoArray = [[NSArray alloc] initWithArray:array1];
        }
            break;
        default:
            break;
    }
    
    //背景button
    UIView *bgView = [[UIView alloc]initWithFrame:self.bounds];
    [bgView setBackgroundColor:[UIColor blackColor]];
    [bgView setTag:BgViewTag];
    [bgView setAlpha:0];
    [self addSubview:bgView];
    
    //
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
    [view setBackgroundColor:[UIColor clearColor]];
    [self addSubview:view];
    
    UIView *pickView = nil;
    if (datePick) {
        //时间选择器
        UIDatePicker *datePicker = [[UIDatePicker alloc]init];
        if (currentType == SZ_CZTX_TZ) {
            [datePicker setDatePickerMode:UIDatePickerModeTime];
            if (oldText.length>0) {
                NSDate *date = [z_DateTime dencodeTime:oldText format:@"HH:mm"];
                [datePicker setDate:date];
            }
        }else{
            if (oldText.length>0) {
                NSDate *date = [z_DateTime dencodeTime:oldText format:APP_SELECTPICKERVIEW_DATE_FORMAT];
                [datePicker setDate:date];
            }
            if (currentType == CSRQ_TYPE) {
                [datePicker setMinimumDate:[z_DateTime dencodeTime:@"1920-01-01" format:APP_SELECTPICKERVIEW_DATE_FORMAT]];
                [datePicker setMaximumDate:[z_DateTime dencodeTime:@"1999-12-31" format:APP_SELECTPICKERVIEW_DATE_FORMAT]];
            }else{
                [datePicker setMaximumDate:[NSDate date]];
            }
            [datePicker setDatePickerMode:UIDatePickerModeDate];
        }
        [datePicker setBackgroundColor:[UIColor whiteColor]];
        [datePicker setTag:UIDatePickerTag];
        [view addSubview:datePicker];
        pickView = datePicker;
    }else{
        //非时间选择器
        UIPickerView *picker = [[UIPickerView alloc]init];
        [picker setBackgroundColor:[UIColor whiteColor]];
        [picker setShowsSelectionIndicator:YES];
        [picker setTag:UIDatePickerTag];
        [picker setDelegate:self];
        [picker setDataSource:self];
        [view addSubview:picker];
        pickView = picker;
        
        if (!twoArray && oldText.length>0) {
            if (currentType == XZMZ_TYPE) {
                [picker selectRow:[NationClass getNameLoc:oldText] inComponent:0 animated:NO];
            }else{
                if ([oneArray containsObject:oldText]) {
                    [picker selectRow:[oneArray indexOfObject:oldText] inComponent:0 animated:NO];
                }
            }
        }else if (twoArray && oldText.length>0){
            NSRange range = [oldText rangeOfString:@"."];
            if (range.length > 0) {
                NSString *text1 = [oldText substringToIndex:range.location];
                NSString *text2 = [oldText substringFromIndex:range.location];
                [picker selectRow:[oneArray indexOfObject:text1] inComponent:0 animated:NO];
                [picker selectRow:[twoArray indexOfObject:text2] inComponent:1 animated:NO];
            }
        }
    }

    //背景button
    UIView *colorView = [[UIView alloc]initWithFrame:self.bounds];
    [colorView setBackgroundColor:GET_COLOR(@"ff8cb7")];
    [colorView setFrame:CGRectMake(0, 0, self.frame.size.width, 44)];
    [view addSubview:colorView];
    
    [view setFrame:CGRectMake(0, self.frame.size.height, self.frame.size.width, pickView.frame.size.height+colorView.frame.size.height)];
    [pickView setCenter:CGPointMake(view.frame.size.width/2,view.frame.size.height-pickView.frame.size.height/2)];

    //取消
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelButton setFrame:CGRectMake(10,0,50,colorView.frame.size.height)];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
    [cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cancelButton setShowsTouchWhenHighlighted:YES];
    [cancelButton addTarget:self action:@selector(cancelButt:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:cancelButton];
    
    //完成
    UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [doneButton setFrame:CGRectMake(colorView.frame.size.width-60,0,50,colorView.frame.size.height)];
    [doneButton setTitle:@"确定" forState:UIControlStateNormal];
    [doneButton.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
    [doneButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [doneButton setShowsTouchWhenHighlighted:YES];
    [doneButton addTarget:self action:@selector(doneButt:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:doneButton];
    
    //执行动画效果
    [UIView animateWithDuration:0.3 animations:^(void){
        [bgView setAlpha:0.3];
        [view setCenter:CGPointMake(self.frame.size.width/2, self.frame.size.height-view.frame.size.height/2)];
    }];
}

//取消设置时间
-(void)cancelButt:(UIButton*)button
{
    UIView *view = [button superview];
    UIView *bgView = [self viewWithTag:BgViewTag];
    //执行动画效果
    [UIView animateWithDuration:0.3 animations:^(void){
        [bgView setAlpha:0];
        [view setCenter:CGPointMake(self.frame.size.width/2, self.frame.size.height+view.frame.size.height/2)];
    } completion:^(BOOL ss){
        [self removeFromSuperview];
    }];
}

//完成设置时间
-(void)doneButt:(UIButton*)button
{
    [self cancelButt:button];
    
    NSString *text = nil;
    if (oneArray) {
        UIPickerView *pickerView = (UIPickerView*)[[button superview] viewWithTag:UIDatePickerTag];
        NSInteger row1 = [pickerView selectedRowInComponent:0];
        if (currentType == XZMZ_TYPE) {
            text = [[oneArray objectAtIndex:row1] valueForKeyPath:@"nation"];
        }else{
            text = [oneArray objectAtIndex:row1];
            if (twoArray) {
                NSInteger row2 = [pickerView selectedRowInComponent:1];
                text = [text stringByAppendingString:[twoArray objectAtIndex:row2]];
            }
        }
    }else{
        UIDatePicker *datePicker = (UIDatePicker*)[[button superview] viewWithTag:UIDatePickerTag];
        if (currentType == SZ_CZTX_TZ) {
            text = [z_DateTime encodeTime:[datePicker date] format:@"HH:mm"];
        }else{
            text = [z_DateTime encodeTime:[datePicker date] format:APP_SELECTPICKERVIEW_DATE_FORMAT];
        }
    }
    
    if ([(NSObject*)self.delegate respondsToSelector:@selector(selectedText:)]) {
        [self.delegate selectedText:text];
    }
    
}

#pragma mark - UIPickerViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    if (twoArray) {
        return 2;
    }
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0 ) {
        return oneArray.count;
    }
    return twoArray.count;
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0 ) {
        if (currentType == XZMZ_TYPE) {
            return [[oneArray objectAtIndex:row] valueForKeyPath:@"nation"];
        }
        return [oneArray objectAtIndex:row];
    }
    return [twoArray objectAtIndex:row];
}

//#pragma mark - 民族数据
////读取民族数据
//-(NSArray*)readNationData:(NSString*)oldText
//{
//    NSString *text = [APP_USERDEFAULTS valueForKey:@"hqmzcg_nation"];
//    if (text) {
//        return [text objectFromJSONString];
//        NSArray *array = [text objectFromJSONString];
//        NSMutableArray *dataArray = [NSMutableArray arrayWithCapacity:1];
//        for (NSDictionary *dic in array) {
//            [dataArray addObject:[dic valueForKey:@"nation"]];
//        }
//        return dataArray;
//    }
//    [LoadingFrameView showLoadingview];
//    NSDictionary *dic = @{IOS_METHOD_NAME: IOS_NATION};
//    ASIHTTPRequest *request =  [NetUtls httpGet:self withValue:dic tag:IOS_NATION_TAG need:YES];
//    request.userInfo = @{@"key": oldText};
//    [request startAsynchronous];
//    return nil;
//}
//
//#pragma mark - ASIHTTPRequestDelegate
//-(void)requestFinished:(ASIHTTPRequest *)request
//{
//    CLog(@"request====%@",[request responseString]);
//    id data = [[request responseString] objectFromJSONString];
//    if ([data isKindOfClass:[NSArray class]]) {
//        //
//        CLog(@"获取民族成功");
//        //保存民族信息
//        [APP_USERDEFAULTS setValue:[request responseString] forKey:@"hqmzcg_nation"];
//        
//        [self setShowView:XZMZ_TYPE text:[request.userInfo valueForKey:@"key"]];
//        [LoadingFrameView directlyDisappear];
//    }else{
//        [self requestFailed:request];
//    }
//}
//
//-(void)requestFailed:(ASIHTTPRequest *)request
//{
//    CLog(@"request====%@",[request responseString]);
//    [LoadingFrameView autoDisappearTipview:@"获取民族失败"];
//}

@end
